package com.fjut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjut.mapper.ChapterMapper;
import com.fjut.model.vod.Chapter;
import com.fjut.model.vod.Video;
import com.fjut.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjut.service.VideoService;
import com.fjut.vo.vod.ChapterVo;
import com.fjut.vo.vod.VideoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.fjut.dateBase.ChapterField.COURSE_ID;


/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author DengTianxun
 * @since 2023-03-06
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterVo> getNestedTreeList(Long courseId) {
        List<ChapterVo> chapterVos = new ArrayList<>();
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();

        wrapper.eq(COURSE_ID,courseId);
        videoQueryWrapper.eq(COURSE_ID,courseId);

        List<Chapter> chapters = baseMapper.selectList(wrapper);
        List<Video> videos = videoService.list(videoQueryWrapper);

        chapters.forEach(chapter -> {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            ArrayList<VideoVo> videoVos = new ArrayList<>();
            videos.forEach(video -> {
                VideoVo videoVo = new VideoVo();
                if (video.getChapterId() == chapter.getId()) {
                    BeanUtils.copyProperties(video,videoVo);
                    videoVos.add(videoVo);
                }
            });
            chapterVo.setChildren(videoVos);
            chapterVos.add(chapterVo);
        });
        return chapterVos;
    }

    @Override
    public void removeChapterByCourseId(Long id) {
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        if (id == null) {
            return;
        }
        wrapper.eq(COURSE_ID,id);
        baseMapper.delete(wrapper);
    }

}
